<?php

/**
 * @author CHUN Dany <chundany@gmail.com>
 */
class Mod_Category extends CI_Model
{	
	public function getCategory($start, $num)
  {
		$this->db->select('c.*, p.'.field('name').' AS '.field('parent'))
        ->from(table('category').' c')
        ->join(table('category').' p', 'c.'.field('parentId').'= p.'.field('id'), 'left')
        ->order_by('c.'.field('updatedAt'), 'DESC');

		$this->db->limit($num, $start);

    return $this->db->get();
	}
	
  public function getCategoryNum()
  {
    $objDb = $this->getAllCategory();
    return $objDb->num_rows();
  }
	
  public function getAllCategory() {
    $this->db->select('c.*, p.'.field('name').' AS '.field('parent'))
        ->from(table('category').' c')
        ->join(table('category').' p', 'c.'.field('parentId').'= p.'.field('id'), 'left')
        ->order_by('c.'.field('updatedAt'), 'DESC');

  	return $this->db->get();
  }
	
  public function getCategoryById($id)
  {
    $this->db->select('c.*, p.'.field('name').' AS '.field('parent'))
        ->from(table('category').' c')
        ->join(table('category').' p', 'c.'.field('parentId').'= p.'.field('id'), 'left')
        ->where('c.'.field('id'), $id);

		$result = $this->db->get();

		return $result->row_array();
  }
	
	public function getCategoryList($id = NULL)
  {
		$this->db->select(field('id') . ', ' . field('name'))
        ->from(table('category'))
        ->where(field('isDisable'), 0)
        ->where(field('parentId'), 0);

		if(!empty($id))
			$this->db->where(field('id').' !=', $id);
		$this->db->order_by(field('name'), 'ASC');
		$result = $this->db->get();
		
		$return = array('' => '');
		if($result->num_rows() > 0){
			foreach($result->result_array() as $row){
				$return[$row[field('id')]] = $row[field('name')];
			}
		}

		return $return;
	}
	
	public function insert($name, $parent, $description)
  {
		$data = array(
			field('name')		    => $this->input->post('name'), 
			field('parentId') 	=> $this->input->post('parent', 0),
			field('description')=> $this->input->post('description')
		);
		
		$this->db->insert(table('category'), $data); 
		return $this->db->affected_rows();
	}
	
	public function update($id)
  {
    $disable  = $this->input->post('disable', false);
		$data = array(
      field('name')       => $this->input->post('name'), 
      field('parentId')   => $this->input->post('parent', 0),
      field('description')=> $this->input->post('description'),
			field('isDisable')	  => ($disable == 1 ? 1 : 0)
		);
		$this->db->set(field('updatedAt'), 'NOW()', FALSE);
		
    $this->db->where(field('id'),$id);
		$this->db->update(table('category'), $data);

		return $this->db->affected_rows();
	}
	
  public function delete($id)
  {
    $this->db->where(field('id'), $id);
    $this->db->delete(table('category'));

    return $this->db->affected_rows();
  }
}